//创建用户相关的小仓库
import { defineStore } from 'pinia'
import { login, register, getInfo } from '@/api/user'

import encrypt from '@/utils/encrypt'
//创建用户小仓库
const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: () => {
    return {
      token: null, //用户唯一标识token
      username: '',
      avatar: '',
      roles: []
    }
  },
  //异步|逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(userInfo) {
      const { username, password } = userInfo
      const encryptPwd = await encrypt(password)
      const postUserInfo = { username, password: encryptPwd }
      //登录请求
      try {
        const { data } = await login(postUserInfo)
        console.log('data: ', data)
        this.token = data.token
        return '登录成功'
      } catch (error) {
        console.log('error: ', error)
        return Promise.reject(new Error(error))
      }
    },
    async userRegister(userInfo) {
      const { username, password, email } = userInfo
      const encryptPwd = await encrypt(password)
      const postUserInfo = { username: username.trim(), password: encryptPwd, email: email.trim() }
      //注册请求
      try {
        const { data } = await register(postUserInfo)
        console.log('data: ', data)
        this.token = data.token
        return '注册成功'
      } catch (error) {
        console.log('error: ', error)
        return Promise.reject(new Error(error))
      }
    },
    //获取用户信息方法
    async userInfo() {
      try {
        const { data } = await getInfo()
        console.log('data: ', data)
        const { roles, username, avatar } = data
        this.roles = roles
        this.username = username
        this.avatar = avatar
      } catch (error) {
        return Promise.reject(new Error(error))
      }
    },
    //退出登录
    async userLogout() {}
  },
  getters: {}
})
//对外暴露获取小仓库方法
export default useUserStore
